package com.example.ricebibackend.controller;

import com.example.ricebibackend.common.errorcode.ControllerErrorCodeConstants;
import com.example.ricebibackend.common.exception.ControllerException;
import com.example.ricebibackend.common.pojo.CommonResult;
import com.example.ricebibackend.common.utils.JacksonUtil;
import com.example.ricebibackend.controller.param.ChartShowParam;
import com.example.ricebibackend.controller.result.ChartShowResult;
import com.example.ricebibackend.controller.result.ChartShowSingleResult;
import com.example.ricebibackend.service.ChartService;
import com.example.ricebibackend.service.dto.ChartShowDTO;
import com.example.ricebibackend.service.dto.ChartShowSingleDTO;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/chart")
public class ChartController {

    private static final Logger logger = LoggerFactory.getLogger(ChartController.class);

    @Resource
    private ChartService chartService;

    @PostMapping("/show")
    public CommonResult<ChartShowResult> showChart(@RequestBody ChartShowParam param) {
        // 日志记录
        logger.info("ChartController showChart方法接收到参数: {}", JacksonUtil.writeValueAsString(param));
        ChartShowDTO chartShowDTO = chartService.getChartListByUploadUserId(param);
        ChartShowResult chartShowResult = convertToChartShowResult(chartShowDTO);
        return CommonResult.success(chartShowResult);
    }

    private ChartShowResult convertToChartShowResult(ChartShowDTO chartShowDTO) {
        // 参数校验
        if (chartShowDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.CHART_SHOW_ERROR);
        }
        ChartShowResult chartShowResult = new ChartShowResult();
        List<ChartShowSingleResult> chartShowSingleResultList = new ArrayList<>();
        for (ChartShowSingleDTO dto : chartShowDTO.getData()) {
            ChartShowSingleResult chartShowSingleResult = new ChartShowSingleResult();
            chartShowSingleResult.setId(dto.getId());
            chartShowSingleResult.setChartName(dto.getChartName());
            chartShowSingleResult.setChartType(dto.getChartType());
            chartShowSingleResult.setGoal(dto.getGoal());
            chartShowSingleResult.setGenData(dto.getGenData());
            chartShowSingleResult.setGenResult(dto.getGenResult());
            chartShowSingleResultList.add(chartShowSingleResult);
        }
        chartShowResult.setData(chartShowSingleResultList);
        chartShowResult.setTotal(chartShowDTO.getTotal());
        return chartShowResult;
    }
}
